<template>
  <div class="app-container">
    <div class="searchStyle">
      <div class="searchStyle">
        <div>
          <el-input
            v-model="queryParams.facilityName"
            placeholder="组织名称查询查询"
            :prefix-icon="Search"
            style="width: 200px;margin-right: 15px;"
            @keyup.enter="handleQuery"
          />
        </div>
      </div>
      <div>
        <el-button
          type="primary"
          plain
          @click="handleAdd"
          v-hasPermi="['system:setting:add']"
          >新建</el-button
        >
        <!-- <el-button
          type="warning"
          plain
          @click="handleExport"
          v-hasPermi="['system:setting:export']"
          >导入</el-button
        > -->
      </div>
    </div>

    <el-table v-loading="loading" :data="settingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公共设施名称" align="center" prop="facilityName" />
      <el-table-column label="地理位置" align="center" prop="geographicalLocation" />
      <el-table-column label="营业时间" align="center" prop="businessHour">
        <template #default="scope">
          <div v-for="(item, index) in (typeof scope.row.businessHour === 'string' ? JSON.parse(scope.row.businessHour) : scope.row.businessHour)" :key="index">
            {{ item.value[0] }} 至 {{ item.value[1] }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="场所责任人" align="center" prop="responsibleName">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            link
            type="danger"
            text='danger'
            icon="Delete"
            @click="deleteNode(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

     <!-- 新增【请填写功能名称】对话框 -->
     <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="settingRef" :model="form" :rules="rules" label-width="110px" label-position="top">
        <el-form-item label="公共设施名称" prop="facilityName">
          <el-input v-model="form.facilityName" placeholder="请输入公共设施名称" />
        </el-form-item>

        <el-form-item label="场所责任人" prop="responsibleId">
          <el-tree-select
            v-model="form.responsibleId"
            :data="userOptions"
            :render-after-expand="false"
            show-checkbox
            :props="{
              value: 'id',
              label: 'label',
              children: 'children',
              // 可选：禁用用户节点选择
              disabled: (data) => !data.isUser
            }"
            check-strictly
            check-on-click-node
            node-key='id'
            filterable
            style="width: 100%"
            placeholder="选择排班责任人"
          />
        </el-form-item>

        <el-form-item label="概况">
          <el-input v-model="form.description" placeholder="请输入概况"  type="textarea" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="面积">
              <el-input v-model.number="form.area"  type="number" placeholder="请输入面积" >
                <template #append>平方米</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="层高">
              <el-input v-model.number="form.storeyHeight"  type="number" placeholder="请输入层高" >
                <template #append>米</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最高容纳人数">
              <el-input v-model.number ="form.capacity"   type="number" placeholder="请输入最高容纳人数" >
                <template #append>人</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="地理位置" prop="geographicalLocation">
          <el-input v-model="form.geographicalLocation" placeholder="请输入概况"  type="textarea" />
        </el-form-item>

        <el-form-item 
          label="营业时间" 
          prop="businessHour" 
          class="hours"
        >
          <el-row>
            <el-col :span="24"  v-for="(domain, index) in form.businessHour" :key="index">
              <el-time-picker
                style="width: 95%;margin: 3px 0;"
                v-model="domain.value"
                is-range
                range-separator="至"
                value-format="HH:mm:ss"
              />
              <el-button
                v-if="form.businessHour.length > 1"
                link
                type="danger"
                text='danger'
                icon="Delete"
                @click="hoursDelete(index)"
                ></el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-button
            link
            type="primary"
            icon="CirclePlus"
            @click="addDomain"
            >添加</el-button
          >
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="publicFacilities">
import { Calendar, Search, Share } from "@element-plus/icons-vue"
import {
  facilityList,
  addFacility,
  putFacility,
  delSettingFacilityIds
} from "@/api/system/setting"
import useUserStore from "@/store/modules/user"
import { deptUserTree } from "@/api/system/role"
import { ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance()

const settingList = ref([])
const open = ref(false)
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {
    facilityName: null,
    responsibleId: null,
    geographicalLocation: null,
    description: null,
    area: null,
    capacity: null,
    storeyHeight: null,
    businessHour: [{value:[]}],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    facilityName: null,
  },
  rules: {
    facilityName: [{ required: true, message: "公共设施名称不能为空", trigger: "blur" }],
    responsibleId: [{ required: true, message: "场所责任人不能为空", trigger: "change" }],
    geographicalLocation: [{ required: true, message: "地理位置不能为空", trigger: "blur" }],
    businessHour: [{ required: true, validator: (rule, value, callback) => {
      let is = false
      value.forEach((item) => {
        if(item.value.length > 0) {
          is = true
        }
      })
      if(is) {
        callback()
        return
      }else{
        callback(new Error("营业时间不能为空"))
        return
      }
    }, trigger: "change" }],
  },
})

const { queryParams, form, rules } = toRefs(data)


const userOptions = ref([])

// 获取下拉数据
useUserStore().getInfo().then((res)=>{
  // 获取责任人
  deptUserTree({deptId:res.user.dept.deptId}).then((response) => {
    if(response.code == 200) {
      userOptions.value = [transformDeptTree(response.data,true)]
    }
  })
})

/** 查询【请填写功能名称】列表 */
function getList() {
  loading.value = true
  facilityList(queryParams.value).then((response) => {
    settingList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    facilityName: null,
    responsibleId: null,
    responsibleBy: null,
    description: null,
    area: null,
    capacity: null,
    storeyHeight: null,
    businessHour: [{value:[]}],
  }
  proxy.resetForm("settingRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.slaId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "新建公共设施"
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["settingRef"].validate((valid) => {
    if (valid) {
      let data = {
        "facilityName": form.value.facilityName,
        "geographicalLocation": form.value.geographicalLocation,
        "businessHour": JSON.stringify(form.value.businessHour),
        "responsibleId": form.value.responsibleId,
        "area": form.value.area,
        "storeyHeight": form.value.storeyHeight,
        "capacity": form.value.capacity,
        "description":  form.value.description,
        "hotelId": 220
      }
      if(form.value.facilityId){
        data.facilityId = form.value.facilityId
        putFacility(data).then((response) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      }else{
        addFacility(data).then((response) => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}



/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/setting/export",
    {
      ...queryParams.value,
    },
    `setting_${new Date().getTime()}.xlsx`
  )
}

getList()



/** 修改按钮操作 */
function handleUpdate(row) {
  open.value = true
  form.value = JSON.parse(JSON.stringify(row))
  form.value.businessHour = JSON.parse(form.value.businessHour)
  form.value.responsibleId = Number(form.value.responsibleId)
  title.value = "修改公共设施"
}

const addDomain = () => {
  form.value.businessHour.push({
    value: [],
  })
}

const hoursDelete = (index) => {
  form.value.businessHour.splice(index, 1)
}

// 删除按钮操作
const deleteNode = (node) => {
  ElMessageBox.confirm(
    '确定删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
    .then(() => {
      delSettingFacilityIds(node.facilityId).then((response) => {
        proxy.$modal.msgSuccess("删除成功")
        getList()
      })
    })
    .catch(() => {
    })
};

function transformDeptTree(deptNode, isRoot = false) {
  // 1. 处理当前部门节点
  const transformedNode = {
    id: deptNode.deptId,
    label: deptNode.deptName,
    children: []
  };

  // 2. 合并用户到同层级children（优先处理用户）
  if (deptNode.userList?.length > 0) {
    transformedNode.children.push(
      ...deptNode.userList.map(user => ({
        id: user.userId,
        label: `${user.nickName} (${user.userName})`,
        isUser: true
      }))
    );
  }

  // 3. 递归处理子部门
  if (deptNode.children?.length > 0) {
    transformedNode.children.push(
      ...deptNode.children.map(child => transformDeptTree(child))
    );
  }

  // 4. 根节点特殊处理：将第一个子元素移到最前
  if (isRoot && transformedNode.children.length > 0) {
    const firstChild = transformedNode.children.shift();
    transformedNode.children.unshift(firstChild); // 显式确保顺序
  }

  // 5. 处理空children
  if (transformedNode.children.length === 0) {
    delete transformedNode.children;
  }

  return transformedNode;
}

</script>
<style scoped lang="scss">
.searchStyle {
  display: flex;
  margin-bottom: 10px;
}
.hours{
  width: 100%;
  ::v-deep .el-form-item__content {
    width: 100%;
    display: flex;
    flex-direction: column;
    .el-row{
      width: 100%;
    }
  }
}
</style>

